﻿/*****************************************************************
 * Copyright (C) Newegg Corporation. All rights reserved.
 * 
 * Author       :  Bill Li (Bill.S.Li@newegg.com)
 * Create Date  :  
 * Usage        :  
 *
 * RevisionHistory
 * Date         Author               Description
 * 
*****************************************************************/
using System.Text;
using System.Xml;
using Framework;

namespace TemplateEngine.TranslateCommand
{
    internal class EachTranslate : ITranslate
    {
        private int _idx = 0;

        public int Index
        {
            get
            {
                return _idx;
            }
        }

        public string Translate(TemplateNode node, XmlNode xmlNode)
        {
            string path = node.Attributes["select"];
            if (string.IsNullOrEmpty(path))
            {
                TemplateEngineException ex = new TemplateEngineException( "each节点必须定义select属性！");
                TemplateLogger.Error(ex);
                throw ex;
            }

            StringBuilder result = new StringBuilder();
            foreach (XmlNode each_node in xmlNode.SelectNodes(path))
            {
                _idx++;
                string temp = node.ResultStr;
                foreach (TemplateNode template_node in node.Nodes)
                {
                    string str = template_node.TranslateNode(each_node);
                    string guid = template_node.NodeGuid.ToString("N");

                    temp = temp.Replace("{[" + guid + "]}", str);
                }

                result.Append(temp);

            }

            return result.ToString();
        }
    }
}
